package com.yupi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.model.entity.UserInterfaceInfo;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.service.UserInterfaceInfoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
/**
* @author Administrator
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2024-08-01 11:21:46
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Override
    public void validuserinterfaceinfo(UserInterfaceInfo userinterfaceinfo, boolean b) {
        final Long userId = userinterfaceinfo.getUserId();
        final Long interfaceInfoId = userinterfaceinfo.getInterfaceInfoId();
        if(userId <= 0 || interfaceInfoId <= 0 ){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口id或调用用户id不存在");
        }
        final Integer leftNum = userinterfaceinfo.getLeftNum();
        if(leftNum < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口剩余调用次数错误");
        }
    }


    /**
     * 统计接口调用的次数（要完成这个功能，只需要一个用户的id和接口的id即可）
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokecount(Long interfaceInfoId, Long userId) {
        if(interfaceInfoId <= 0){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"请求接口的id不存在");
        }
        if(userId <= 0){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"请求用户的id不存在");
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.eq("userId", userId);

//        updateWrapper.gt("leftNum", 0);
        updateWrapper.setSql("leftNum = leftNum - 1, totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }

}




